package com.mkl.ttxt.remote.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.mkl.ttxt.common.exception.LoginException;
import com.mkl.ttxt.remote.bo.TtxtUser;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

public class TokenUtil {

    private static String key = "RK18HT6DYLToWdDj";
    // 24 hour
    public static final long EXPIRATION_TIME = 24*3600000L;

    private final static ConcurrentHashMap<Integer, String> onlineMap = new ConcurrentHashMap<>();

    public static String getToken(TtxtUser user, Date loginDate) {
        String token="";
        if(1 == user.getUserId()){
            token= JWT.create().withAudience(String.valueOf(user.getUserId()))
                    .sign(Algorithm.HMAC256(key));
        }else{
            token= JWT.create().withAudience(String.valueOf(user.getUserId()))
                    .withExpiresAt(new Date(loginDate.getTime() + EXPIRATION_TIME))
                    .withNotBefore(new Date())
                    .sign(Algorithm.HMAC256(key));
        }
        return token;
    }

    public static Integer explainToken(String token) {
        String userId = JWT.decode(token).getAudience().get(0);
        return Integer.valueOf(userId);
    }

    public static void loginRecordToken(Integer userId, String token){
        onlineMap.put(userId, token);
    }

    public static void verify(Integer userId, String token) {
//        if(onlineMap.containsKey(userId)){
//            if(!token.equals(onlineMap.get(userId))){
//                throw new LoginException("登录信息已失效，请重新登陆");
//            }
//        }
    }
}
